<!-- 维修列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <!-- <a-button type="primary" @click="repairFault">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>故障报修</template>
      </a-button> -->
      <!-- <a-button
        type="primary"
        :style="{
          backgroundColor: '#31C27C',
          color: '#fff',
        }"
        @click="newRepair"
      >
        <template #icon>
          <icon-subscribe-add></icon-subscribe-add>
        </template>
        <template #default>新建维修任务</template>
      </a-button> -->
    </template>
  </pageHeader>
  <div class="content">
    <div class="content-header">
      <div>
        <a-input-group>
          <a-select
            :style="{
              flex: 1,
              backgroundColor: '#fff',
            }"
            v-model="currSelectName"
            placeholder="请选择"
            @change="search"
          >
            <a-option value="number">维修单号</a-option>
            <a-option value="equipNumber">设备编码</a-option>
          </a-select>
          <a-input-search
            search-button
            :style="{
              flex: 3,
              backgroundColor: '#fff',
              border: '1px solid #ccc',
            }"
            placeholder="请输入"
            v-model="currNumber"
            @change="search"
          >
          </a-input-search>
        </a-input-group>
      </div>
      <div
        :style="{
          marginLeft: '20px',
        }"
      >
        <!-- <span> 设备名称： </span> -->
        <a-input
          :style="{ width: 'auto' }"
          placeholder="请输入设备名称"
          v-model="currEquipName"
          search-button
          @change="search"
        >
          <template #prefix>设备名称：</template>
          <!-- <template #button-icon>
            <icon-search />
          </template> -->
        </a-input>
      </div>
      <a-button
        type="primary"
        :style="{
          marginLeft: '10px',
        }"
        @change="search"
      >
        <template #icon>
          <icon-search />
        </template>
        <template #default>搜索</template>
      </a-button>

      <a-button
        type="outline"
        :style="{
          marginLeft: '10px',
          borderColor: '#ccc',
          color: '#ccc',
        }"
        @click="reset"
      >
        <template #icon>
          <icon-refresh />
        </template>
        <template #default>重置</template>
      </a-button>
      <!-- <div
        :style="{
          marginLeft: '10px'
        }"
      > -->
      <!-- <span> 维修状态： </span> -->
      <!-- <div>
          <a-select
            placeholder="请选择"
            v-model="currRepairState"
            @change="search"
          >
            <template #prefix>维修状态：</template>
            <a-option :value="0">全部</a-option>
            <a-option :value="1">待派工</a-option>
            <a-option :value="2">待维修</a-option>
            <a-option :value="3">进行中</a-option>
            <a-option :value="4">需委外</a-option>
            <a-option :value="5">已委外</a-option>
            <a-option :value="6">已完工</a-option>
          </a-select>
        </div>
      </div> -->

      <a-button
        type="outline"
        :style="{
          margin: '0 5px 0 10px',
          borderColor: '#4cd263',
          color: '#4cd263',
        }"
      >
        <template #icon>
          <icon-download />
        </template>
        <template #default>导入</template>
      </a-button>
      <a-button
        type="outline"
        :style="{
          margin: '0 10px 0 5px',
          borderColor: '#ffcf8b',
          color: '#ffcf8b',
        }"
      >
        <template #icon>
          <icon-export :rotate="-90" />
        </template>
        <template #default>导出</template>
      </a-button>
      <div
        :style="{
          marginLeft: '10px',
        }"
      >
      </div>
    </div>

    <!-- <div
      :style="{
        marginTop: '20px',
        cursor: 'pointer'
      }"
      @click="goWaitList"
    >
      <div>
        <a-alert banner type="error"
          >设备维修提醒：有
          <span
            :style="{
              color: 'red'
            }"
            >{{ waitJobCount }}</span
          >
          台设备需要维修，请尽快处理！</a-alert
        >
      </div>
    </div> -->

    <div
      :style="{
        marginTop: '20px',
      }"
    >
      <TableTurn
        :args="args"
        :table-data="getData"
        ref="tableRef"
        :pageChangeDiy="pageChangeDiy"
      >
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="维修单号"
          data-index="number"
        >
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="设备名称"
          data-index="equipName"
        >
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="设备编码"
          data-index="equipNumber"
        >
        </a-table-column>
        <!-- <a-table-column :width="150" align="center" title="故障描述">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record, 2)">查看</a-button>
          </template>
        </a-table-column> -->

        <a-table-column
          :width="150"
          align="center"
          title="报修人"
          data-index="reporterName"
        >
        </a-table-column>
        <a-table-column :width="200" align="center" title="报修时间">
          <template #cell="{ record }">
            {{ `${dayjs(record.reporterTime).format('YYYY-MM-DD HH:mm:ss')}` }}
          </template>
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="维修人"
          data-index="repairerName"
        >
        </a-table-column>
        <a-table-column :width="200" align="center" title="维修开始时间">
          <template #cell="{ record }">
            {{
              record.repairBeginTime === 0
                ? '-'
                : `${dayjs(record.repairBeginTime).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )}`
            }}
          </template>
        </a-table-column>

        <a-table-column :width="200" align="center" title="维修结束时间">
          <template #cell="{ record }">
            {{
              record.repairEndTime === 0
                ? '-'
                : `${dayjs(record.repairEndTime).format('YYYY-MM-DD HH:mm:ss')}`
            }}
          </template>
        </a-table-column>
        <!-- <a-table-column :width="150" align="center" title="故障分析及处理">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record, 4)">查看</a-button>
          </template>
        </a-table-column> -->
        <a-table-column
          :width="150"
          align="center"
          title="维修状态"
          fixed="right"
        >
          <template #cell="{ record }">
            <div class="repair-state">
              <div
                class="cycle"
                :class="
                  record.repairState === 1
                    ? 'waitJob-cycle'
                    : record.repairState === 2
                    ? 'waitRepair-cycle'
                    : record.repairState === 3
                    ? 'running-cycle'
                    : record.repairState === 4
                    ? 'needOut-cycle'
                    : record.repairState === 5
                    ? 'outing-cycle'
                    : 'finish-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.repairState === 1
                    ? 'waitJob'
                    : record.repairState === 2
                    ? 'waitRepair'
                    : record.repairState === 3
                    ? 'running'
                    : record.repairState === 4
                    ? 'needOut'
                    : record.repairState === 5
                    ? 'outing'
                    : 'finish'
                "
                >{{
                  record.repairState === 1
                    ? '待派工'
                    : record.repairState === 2
                    ? '待维修'
                    : record.repairState === 3
                    ? '进行中'
                    : record.repairState === 4
                    ? '需委外'
                    : record.repairState === 5
                    ? '已委外'
                    : '已完工'
                }}</div
              >
            </div>
          </template>
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell="{ record }">
            <a-button
              type="text"
              :style="{
                backgroundColor: '#31C27C',
                color: '#fff',
              }"
              v-if="record.repairState === 2"
              @click="goDetail(record, 15)"
            >
              开始检修
            </a-button>

            <a-button
              v-if="record.repairState === 6"
              type="text"
              @click="goDetail(record, 5)"
            >
              维修详情
            </a-button>
            <a-button
              v-if="record.repairState === 3"
              type="text"
              @click="goDetail(record, 15)"
            >
              编辑
            </a-button>
            <a-popconfirm
              v-if="!(record.repairState === 2)"
              @ok="deleteItem(record.id)"
              content="确定删除吗"
              type="error"
            >
              <a-button
                type="text"
                :style="{
                  color: 'red',
                }"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </a-table-column>
      </TableTurn>
      <equipmentRepair
        :type="type"
        :form="form.list"
        v-model:visible="repairVisible"
        @equipmentEmit="equipmentEmit"
      ></equipmentRepair>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useUserStore } from '@/store';
  import { useRouter } from 'vue-router';
  import { reactive, ref, onMounted, watchEffect } from 'vue';
  import dayjs from 'dayjs';
  import {
    PostFaultEquipment,
    GetFaultEquipmentList,
    DelFaultEquipment,
    PutFaultEquipment,
  } from '@/api/equipment-management/equipment-maintain-manager';
  import { PutEquipment } from '@/api/equipment-management/equipment-list';
  import { util_d$1 } from 'echarts/types/dist/shared';
  import { cloneDeep } from 'lodash';
  import equipmentRepair from '../../components/equipment-repair/index.vue';

  const userStore = useUserStore();
  const router = useRouter();
  const title: string = '设备待维修列表';
  const breadCrumb: string[] = [
    '设备管理',
    '设备维护（员工）',
    '设备待维修列表',
  ];

  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
  });

  let tableRef = ref(); // 储存table的ref
  let pagination = { pageNumber: 1, pageSize: 10 };
  const pageChangeDiy = (val: number, key: 'page' | 'size') => {
    pagination[key === 'page' ? 'pageNumber' : 'pageSize'] = val;
    tableRef.value.loadData();
  };
  // 储存某行的信息
  const form = reactive({
    list: {
      equipNumber: '', // 设备编码
      equipName: '', // 设备名称
      workshop: '', // 所属车间
      reportTime: undefined, // 报修时间
      reporterId: undefined, // 报修人id
      repairerId: undefined, // 维修人id
      description: '', // 故障描述
      equipmentRepairPicture: [], // 图片上传
    },
  });

  let type = ref(1); // 判断弹出框的type

  let currNumber = ref(''); // 第一个搜索框
  let currSelectName = ref(''); // 储存第一个搜索框的下拉框值

  let currEquipName = ref(''); // 设备名称搜索框
  let currRepairState = ref(undefined);

  // 点击横幅前往维修待派工列表
  const goWaitList = () => {
    router.push({
      name: 'EquipmentMaintenanceWaitList',
    });
  };
  let waitJobCount = ref(0); // 储存待维修状态的数量
  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };
  const waitJobFn = async () => {
    try {
      waitJobCount.value = 0;
      const { content } = await GetFaultEquipmentList({
        page: 0,
        size: -1,
        repairState: 2,
        authority: 1,
      });
      waitJobCount.value = content.length;
      // 监听键盘事件
      window.addEventListener('keydown', keyDown);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      waitJobFn();
      const id = JSON.parse(sessionStorage.getItem('loginInfo') as string).id;
      const data: any = {};
      if (currNumber.value.trim() !== '')
        data[currSelectName.value] = currNumber.value;
      if (currEquipName.value.trim() !== '')
        data.equipName = currEquipName.value;
      if (currRepairState.value !== undefined)
        data.repairState = currRepairState.value;
      else if (currRepairState.value === 0) data.repairState = '';
      const res: any = await GetFaultEquipmentList({
        page: 0,
        size: -1,
        authority: 1,
        repairState: 2,
        ...data,
      });

      if (res && res?.content && res?.content.length !== 0) {
        res.content = res.content.filter((ele: any) => ele.repairState === 2);
        res.content = res.content.filter((ele: any) => ele.repairerId === id);
        res.pageable.totalItems = res.content.length;
        res.pageable.pageNumber = pagination.pageNumber;
        res.pageable.pageSize = pagination.pageSize;
        res.content.slice(
          (pagination.pageNumber - 1) * pagination.pageSize - 1,
          pagination.pageSize
        );
      }

      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  let repairVisible = ref(false); // 判断故障报修弹出框是否弹出

  // 点击故障报修按钮
  const repairFault = () => {
    type.value = 1;
    repairVisible.value = true;
  };

  // 搜索框事件
  const search = () => {
    tableRef.value.loadData();
  };

  // onMounted();

  // 弹出框的自定义事件
  const equipmentEmit = async (list: any, type: number) => {
    try {
      // 开始维修
      if (type === 15) {
        await PutFaultEquipment({
          id: list.id,
          repairBeginTime: +list.repairBeginTime,
          repairEndTime: +list.repairEndTime,
          isReplaceparts: list.isReplaceparts,
          faultAnalysis: list.faultAnalysis,
          treatmentMeasures: list.treatmentMeasures,
          repairState: 3,
        });
        await PutEquipment({ id: list.equipmentId, useState: 4 });
        tableRef.value.loadData();
        // waitJobCount.value -= 1; // 派工成功后横幅的数字+1
      }

      form.list = {
        equipNumber: '', // 设备编码
        equipName: '', // 设备名称
        workshop: '', // 所属车间
        reportTime: undefined, // 报修时间
        reporterId: undefined, // 报修人id
        repairerId: undefined, // 维修人id
        description: '', // 故障描述
        equipmentRepairPicture: [], // 图片上传
      };
      repairVisible.value = false;
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 表格故障描述中的的查看按钮
  const goDetail = (record: any, currType: number) => {
    type.value = currType;
    form.list = record;
    repairVisible.value = true;
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelFaultEquipment({
        id,
        authority: 1,
      });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 重置
  const reset = () => {
    currNumber.value = '';
    currSelectName.value = '';
    currEquipName.value = '';
    currRepairState.value = undefined;
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .content {
    padding: 10px 40px;

    &-header {
      display: flex;
      width: 100%;
      height: 40px;
      margin-bottom: 10px;
      margin-top: 5px;
      :deep(.arco-btn-secondary) {
        color: #165dff;
      }
    }

    .repair-state {
      display: flex;
      justify-content: center;
      text-align: center;
      .cycle {
        position: relative;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        content: '';
        display: inline-block;
        top: 3px;
        right: 10px;
      }
    }

    // 待派工
    .waitJob {
      color: #ccc;
    }
    .waitJob-cycle {
      background-color: #ccc;
    }

    // 维修中
    .waitRepair {
      color: #ccc;
    }
    .waitRepair-cycle {
      background-color: #ccc;
    }
    // 进行中
    .running {
      color: #3d7eff;
    }
    .running-cycle {
      background-color: #3d7eff;
    }
    // 需委外
    .needOut {
      color: #f90;
    }
    .needOut-cycle {
      background-color: #f90;
    }
    // 已委外
    .outing {
      color: #3cf;
    }
    .outing-cycle {
      background-color: #3cf;
    }
    // 已完工
    .finish {
      color: #31c27c;
    }
    .finish-cycle {
      background-color: #31c27c;
    }
  }
</style>
